import {
  socket
} from '../config/config'
let sotk = null;
export function connectSocket() {
  let uid = wx.getStorageSync('imuid')
  if (!uid) return null
  const host = `${socket}/conversation/on_new_web_push/websocket?uid=${uid}`; // websocket服务器baseUrl
  return wx.connectSocket({
    url: host,
    header: {
      'content-type': 'application/json'
    },
    success: (res) => {
      console.log('WebSocket success ===>', res);
    },
    fail: (err) => {
      console.log('WebSocket fail ====>', err);
    }
  })
}

function ws_connect(options = {}, callback, errback) {
  // 确保只连接1个socket
  if (!sotk) {
    sotk = connectSocket()
  }

  sotk && sotk.onOpen(res => {
    console.log('WebSocket onOpen ====>', res);
  })

  // 收到消息
  sotk && sotk.onMessage(onMessage => {
    callback && callback(onMessage.data);
  })

  sotk && sotk.onClose(onClose => {
    sotk = null
    errback && errback()
    console.log('WebSocket onClose ===>', onClose)
  })

  sotk && sotk.onError(onError => {
    console.log('WebSocket onError ===>', onError)
  })

  if (options && options.close === true) {
    console.log('WebSocket option ===>', options)
    sotk && sotk.close({
      code: 1000,
      success: (res) => {
        console.log('WebSocket closeSocket success ===>', res)
      },
      fail: (err) => {
        console.log('WebSocket closeSocket fail ===>', err)
      }
    })
  }

  return sotk
}

export default ws_connect